import { memo, useEffect, useRef, useState } from "react";
import { ScrollViewWapper } from "./style";
import IconArrowLeft from "@/assets/svg/icon-arrow-left";
import IconArrowRight from "@/assets/svg/icon-arrow-right";

export const ScrollView = memo((props) => {
  const [showRight, setShowRight] = useState(false);
  const [showLeft, setShowLeft] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);
  const scrollContentRef = useRef();
  const totalDistanceRef = useRef();

  useEffect(() => {
    const scrollWidth = scrollContentRef.current.scrollWidth; // 可滚动宽度
    const clientWidth = scrollContentRef.current.clientWidth; // 本身宽度
    const totalDistance = scrollWidth - clientWidth; // 可滚动距离
    totalDistanceRef.current = totalDistance;
    setShowRight(totalDistance > 0);
  }, [props.children]);

  const handleControl = (right) => {
    const index = right ? currentIndex + 1 : currentIndex - 1;
    const el = scrollContentRef.current.children[index];
    const left = el.offsetLeft;
    scrollContentRef.current.style.transform = `translate(-${left}px)`;
    setCurrentIndex(index);
    setShowRight(totalDistanceRef.current > left);
    setShowLeft(left > 0);
  };

  return (
    <ScrollViewWapper>
      {showLeft && (
        <div className="control left" onClick={(e) => handleControl(false)}>
          <IconArrowLeft />
        </div>
      )}
      {showRight && (
        <div className="control right" onClick={(e) => handleControl(true)}>
          <IconArrowRight />
        </div>
      )}
      <div className="scroll">
        <div className="scroll-content" ref={scrollContentRef}>
          {props.children}
        </div>
      </div>
    </ScrollViewWapper>
  );
});

export default ScrollView;
